//
//  DWLogListViewController.m
//  OCAppDemo
//
//  Created by DW on 2020/8/10.
//  Copyright © 2020 DW. All rights reserved.
//

#import "DWLogListViewController.h"
#import "FCFileManager.h"

@interface DWLogListViewController () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) NSArray *fileList;
@property (nonatomic, strong) UITableView *tableView;

@end

@implementation DWLogListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.tableView];
    [self loadAd];
}

- (void)loadAd {
    self.fileList = [FCFileManager listFilesInDirectoryAtPath:self.filePath];
    [self.tableView reloadData];
}

#pragma mark private method

- (void)shareFile:(NSURL *)url {
    NSArray *activityItems = @[url];
    UIActivityViewController *aVC = [[UIActivityViewController alloc] initWithActivityItems: activityItems
                                                                      applicationActivities: nil];
    [aVC setCompletionWithItemsHandler:^(UIActivityType  _Nullable activityType,
                                         BOOL completed,
                                         NSArray * _Nullable returnedItems,
                                         NSError * _Nullable activityError) {
        if (completed) {
            NSLog(@"分享成功");
        }
    }];
    [self presentViewController: aVC animated: YES completion: nil];
}

#pragma mark delegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.fileList.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSString *file = self.fileList[indexPath.row];
    [self shareFile:[NSURL fileURLWithPath:file]];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CrashCell"];
    NSString *file = self.fileList[indexPath.row];
    cell.textLabel.text = file.lastPathComponent;
    cell.textLabel.font = [UIFont systemFontOfSize:14];
    cell.textLabel.numberOfLines = 2;
    return cell;
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] init];
        _tableView.frame = self.view.bounds;
        _tableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [_tableView registerClass:UITableViewCell.class forCellReuseIdentifier:@"CrashCell"];
    }
    return _tableView;
}

@end
